<template>
  <div class="full-height full-width">
    <div>
      <select-sport-type></select-sport-type>
    </div>
    <div class="full-height full-width">
      <!-- 查询条件区域  -->
      <div
        class="col-12"
        id="match-manage-toggle-query-area"
        :style="show_more_query?'height:90px;':'height:30px;'"
      >
  
        <!-- 日期选择组件 -->
        <select-query-period
          :bgclass="'bg-panda-expand-bg-color'"
          @query_period_change="query_period_change"
          @show_more_query_change="show_more_query_change"
        ></select-query-period>
        <div v-if="show_more_query">
          <data-source-code @change="queryform_form_dataSourceCode_change" :not_pa="'1'"></data-source-code>
          <div
            class="row q-px-md line-height-30px items-center q-gutter-x-lg bg-panda-expand-bg-color text-panda-text-dark"
          >
            <q-select
              filled
              rounded
              color="panda-text-light"
              bg-color="panda-light-light"
              style="    width: 170px;"
              v-model="queryform_form.matchStatus"
              hide-bottom-space
              :options="compute_match_status_constant('match_status_constant')"
              emit-value
              map-options
              option-value="value"
              option-label="description"
              dense
              options-dense
              popup-content-class="bg-panda-light-light text-panda-text-light"
            >
              <template v-slot:before>
                <span class="text-panda-text-dark">赛事状态</span>
              </template>
            </q-select>
            <q-select
              filled
              rounded
              color="panda-text-light"
              bg-color="panda-light-light"
              style="    width: 170px;"
              v-model="queryform_form.oddStatus"
              :options="odds_status_constant"
              dense
              emit-value
              map-options
              option-value="value"
              option-label="label"
              options-dense
              popup-content-class="bg-panda-light-light text-panda-text-light"
            >
              <template v-slot:before>
                <span class="text-panda-text-dark">盘口状态：</span>
              </template>
            </q-select>
            <q-select
              filled
              rounded
              color="panda-text-light"
              bg-color="panda-light-light"
              style="width: 160px;"
              v-model="queryform_form.leagueLevel"
              hide-bottom-space
              :options="compute_match_status_constant('match_level_constant')"
              emit-value
              map-options
              option-value="value"
              option-label="description"
              dense
              options-dense
              popup-content-class="bg-panda-light-light text-panda-text-light"
            >
              <template v-slot:before>
                <span class="text-panda-text-dark">联赛级别：</span>
              </template>
            </q-select>
            <q-btn
              class="panda-btn-dense panda-btn-light-dense"
              label="确定"
              @click="tosearch_queryform()"
            />
            <q-space></q-space>
          </div>
        </div>
      </div>
      <!-- 选中项目显示区域   开始 -->
      <div v-if="selected_item_pool.length>0" class="full-width" ref="select">
        <div class="row q-px-md items-center q-gutter-x-sm line-height-30px bg-panda-light-light">
          <span class="panda-round-dot panda-dot-blue"></span>
          <span
            class="text-panda-text-light q-mr-lg"
            v-if="!show_associate_success"
          >共选中{{selected_item_pool.length}}条数据</span>
          <span class="text-panda-text-light q-mr-lg" v-if="show_associate_success">已关联成功</span>
          <q-btn
            v-if="selected_item_pool.length>1"
            class="panda-btn-dense panda-btn-light-dense"
            label="关联为同一赛事"
            @click="handle_associate_or_merge_match"
          />
          <q-btn
            class="panda-btn-dark-dense"
            :label="selected_item_pool.length==1?'关闭': '取消'"
            @click="handle_reset_selected_item_pool"
          />
          <q-space />
        </div>
        <div class="full-width">
          <q-table
            title
            :data="selected_item_pool"
            :columns="tablecolumns"
            dense
            row-key="name"
            class="bg-panda-dark-dark panda-table full-width"
            separator="cell"
            hide-bottom
            hide-header
            :pagination.sync="pagination"
          >
            <template v-slot:body="props">
              <tablerow
                :props="props"
                :is_top_slot="1"
                :tablecolumns="tablecolumns"
                :show_right_detail_obj="show_right_detail_obj"
                :table_col_leagueName_color_map="table_col_leagueName_color_map"
                class="text-panda-text-light"
                @item_click="table_item_click"
                @toggle_select="selected_table_items_change"
              ></tablerow>
            </template>
          </q-table>
        </div>
      </div>
      <!-- 选中项目显示区域   结束 -->
      <!-- 正常列表格展示 -->
      <table-loading :loading="tabledata_loading"/>
      <q-table
        :title="tabletittle"
        :data="tabledata"
        :columns="tablecolumns"
        dense
        row-key="name"
        class="bg-panda-base-dark text-panda-text-light panda-table panda-sticky-header-table full-width"
        table-header-class="panda-table"
        :separator="separator"
        :pagination.sync="pagination"
        :no-data-label="data_label"
        :table-style="`max-height: ${scroll_area_height+30}px;`"
      >
        <!-- :table-style="` min-height: ${scroll_area_height+25}px `" -->

        <!-- <template v-slot:header="props">
  <tableheader :props="props"  :tablecolumns='tablecolumns'></tableheader>
        </template>-->
        <template v-slot:body="props">
          <tablerow
            :props="props"
            :is_top_slot="0"
            :tablecolumns="tablecolumns"
            :table_col_leagueName_color_map="table_col_leagueName_color_map"
            :show_right_detail_obj="show_right_detail_obj"
            @init_tabledata="init_tabledata_force"
            @table_item_click_expanded="table_item_click_expanded"
            @item_click="table_item_click"
            @toggle_select="selected_table_items_change"
            :label_item="label_item"
          ></tablerow>
        </template>
        <template v-slot:bottom>
          <!-- import pandaPagination from "src/components/pagination/pagination.vue" -->
          <panda-pagination
            :total="totalall"
            :tabledata_can_request="tabledata_can_request"
            :queryform_form_changed="queryform_form_changed"
            @handle_currentPage_change="handle_currentPage_change"
            @init_tabledata="init_tabledata"
          ></panda-pagination>
        </template>
      </q-table>
    </div>
     <!-- v-if="showrightdetail" -->
    <div
      class="fixed fixed-right bg-panda-base-dark panda-table border-left text-panda-text-light"
     
      v-if="`${router_cache[$route.name]['showrightdetail']}`"
      style="width:350px;  box-shadow: -1px 0 0 0 rgba(0,0,0,0.50);   top: 61px;  width: 350px; z-index:5"
      :style="right_component_style"
    >
      <right-info :right_detail_obj="show_right_detail_obj" @toedit="to_show_match_edit"></right-info>
    </div>
  </div>
</template>
<style lang="stylus" scoped>
.q-checkbox__inner {
  color: panda-text-light;
}
</style>
<script>
import { mapGetters, mapActions } from "vuex";
import { api_match } from "src/api/index.js";
import mixins from "src/mixins/index.js";

import matchmixin from "src/mixins/pages/match/match.js";
// import { match_manage_tabledata } from "src/mock/match/index.js";
import match_manage_tabledata from "src/mock/match/match_manage.js";
import { tablecolumns_config } from "src/pages/match/manage/config/config.js";
import selectSportType from "src/components/query/selectSportType.vue";
import selectedTableItemMixin from "src/mixins/pages/match/selectedTableItem.js";
import dataSourceCode from "src/components/query/dataSourceCode.vue";
import selectQueryPeriod from "src/components/query/selectQueryPeriod.vue";
import matchStatusmixin from "src/mixins/pages/match/matchStatus.js";

import matchManageMixin from "src/mixins/pages/match/matchManage.js";
import tableheader from "src/components/table/tableheader.vue";
import pandaPagination from "src/components/pagination/pagination.vue";
import tablerow from "src/pages/match/manage/component/tablerow.vue";
import alert_component from "src/config/alert/match.js";
import tableLoading from "src/components/table/tableLoading.vue";

import { dom } from "quasar";
import { createGzip } from 'zlib';
const { height, width } = dom;
export default {
  name: "match_manage",
  mixins: [
    ...mixins,
    matchmixin,
    matchStatusmixin,
    matchManageMixin,
    selectedTableItemMixin
  ],
  components: {
    rightInfo: () => import("src/pages/match/manage/component/rightInfo.vue"),
    openEdit: () => import("src/pages/match/manage/component/openEdit.vue"),
    matchEdit: () => import("src/pages/match/manage/component/matchEdit.vue"),
    miniMatchList: () =>
      import("src/pages/match/manage/component/miniMatchList.vue"),
    selectSportType,
    dataSourceCode,
    selectQueryPeriod,
    tableheader,
    pandaPagination,
    tablerow,
    tableLoading
  },
  data() {
    return {
      queryform_form: {},
      date: "",
      totalall: 0,
      show_more_query: false,
      queryform_module: {
        dataSourceCode: [],
        id: 0,
        leagueLevel: "",
        matchStatus: "",
        oddStatus: "",
        oddStatusFirst: "",
        oddStatusSecond: 0,
        onlyStandard: 0,
        page: 0,
        size: 0,
        startTimeEnd: 0,
        startTimeFrom: 0
      },
      query_form_date_arr: [],
      scroll_area_height: "",
      scroll_area_height: "",
      match_id_state_arr: [
        { label: "全部", value: "100" },
        { label: "有联赛ID", value: "1" },
        { label: "无联赛ID", value: "2" }
      ],
      tab_name: "",
      tabletittle: "",
      show_right_detail: false,
      show_right_detail_obj: {},
      tab2: "",
      show_match_edit: false,
      show_open_edit: false,
      tablecolumns: tablecolumns_config,
      tabledata: [],
      table_col_leagueName_color_map: "",
      label_item: "今日"
    };
  },
  watch: {
    // 监听选中池，改变高度
    selected_item_pool(val) {
      this.when_window_size_info_change();
    },

  },
  beforeCreate() {},
  created() {
    this.tablecolumns = this.rebuild_tablecolumns_config(this.tablecolumns);
  },
  computed: {},
  mounted() {},
  methods: {
    init_tabledata_force() {
      this.init_tabledata_();
    },
    init_tabledata() {
      console.log("表格请求时候的 this.pagination ");
      if (
        this.request_currentPage == this.currentPage &&
        this.currentPage != 1
      ) {
        return false;
      }
      console.log(this.pagination);
      this.init_tabledata_();
    },
    init_tabledata_() {
      /**
       * 这里 暂时不管 全局 的 数据商的 接口 的先后问题  正常情况下 会先返回
       * 后期如果存在问题    加上前置判断和监听
       */
      this.init_tabledata_before();
      let params = this.compute_init_tabledata_params();
      params = this.delete_empty_property_with_exclude(params);

      api_match
        .post_matchManager_queryMatch(params)
        .then(res => {
          this.init_tabledata_after();
          let currentPage =
            this.find_value_in_obj_bypath(res, "res.data.data.page") * 1 || 1;
          if (this.currentPage == currentPage) {
            let arr =
              this.find_value_in_obj_bypath(res, "res.data.data.records") || [];
            this.tabledata = this.rebuild_tabledata_to_needed(arr);
            if (arr[0]) {
              this.table_item_click(arr[0]);
            }
            this.currentPage = currentPage;
            this.request_currentPage = currentPage;
            this.totalall =
              this.find_value_in_obj_bypath(res, "res.data.data.total") * 1 ||
              0;
          } else {
            this.init_tabledata_();
          }
        });
    },

    compute_dataSourceCode_col_color(item) {
      let key = item.dataSourceCode.toLowerCase();
      let val = this.dataSourceCode_color[key];
      return val;
    },
    compute_dataSourceCode_col_dot_data(item) {
      let arr = [];
      item.relatedMatch.map(x => {
        arr.push(x.dataSourceCode);
      });
      arr = Array.from(new Set(arr));
      this.$lodash.pull(arr, item.dataSourceCode);
      // 根据全局 的 数据源 接口 返回  能提供开盘数据的数据商  能商业化的
      let col_dot_color_config = [];
      arr.map(x => {
        col_dot_color_config.push({
          label: x,
          color: this.dataSourceCode_color[x.toLowerCase()]
        });
      });
      col_dot_color_config.unshift({
        label: item.dataSourceCode,
        color: this.dataSourceCode_color[item.dataSourceCode.toLowerCase()]
      });
      return col_dot_color_config;
    },
    compute_match_status_constant(key) {
      key = key || "match_status_constant" 
      if (this.allMatchStaus && this.allMatchStaus[this.sportId]) {
        return (
          this.allMatchStaus[this.sportId][key] || []
        );
      } else {
        return [];
      }
    },
    compute_init_tabledata_params() {
      let params = {};
      params = {
        dataSourceCode: this.queryform_form.dataSourceCode,
        // id: 0,   //编辑页面 单条查询 回显 需要
        leagueLevel: this.queryform_form.leagueLevel,
        matchStatus: this.queryform_form.matchStatus,
        // oddStatusFirst: "",
        // oddStatusSecond: 0,
        // onlyStandard: 0,  编辑页面左侧需要 全部是标准的
        page: this.currentPage,
        size: this.pageSize,
        startTimeEnd: this.queryform_form.startTimeEnd,
        startTimeFrom: this.queryform_form.startTimeFrom,
        sportId:this.sportId
      };
      this.resove_queryform_form_oddStatus(params);
      console.log(" 列表 查询参数");
      console.log(params);
      if (this.queryform_form.dataSourceCode_all) {
        delete params.dataSourceCode;
      }
      return params;
    },
    resove_queryform_form_oddStatus(params) {
      let oddStatus = this.queryform_form.oddStatus;
      console.log(oddStatus);
      if (!oddStatus) {
        params.oddStatusFirst = "";
        params.oddStatusSecond = "";
      } else {
        params.oddStatusFirst = oddStatus.source;
        params.oddStatusSecond = oddStatus.open;
      }
    },
    query_period_change(val) {
      if (val) {
        console.log("  查询日期哦");
        console.log(val);
        this.queryform_form.startTimeFrom = val.startTimeFrom_history;
        this.queryform_form.startTimeEnd = val.startTimeEnd_history;
        this.init_tablecolumns_time(this.queryform_form.startTimeFrom, val.tab);
        this.init_tabledata_force();
      }
    },
    show_more_query_change(val) {
      this.show_more_query = val;
    },
    // 根据选中时间改变标签的值
    init_tablecolumns_time(val, tab) {
      let label_item = this.tablecolumns.find(el => el.name === "beginTime");
      label_item.label =
        tab === 7 ? "其他早盘" : this.format_date_by_manage(val);
      this.label_item = label_item.label;
    },
    to_show_match_edit() {},
    queryform_form_dataSourceCode_change(val) {
      console.log(val);
      this.queryform_form.dataSourceCode = val.dataSourceCode;
      this.queryform_form.dataSourceCode_all = val.dataSourceCode_all;
    },

    table_item_click(item) {
      console.log(" table_item_click(item)");
      console.log(item);
      this.show_right_detail_obj = item;
      this.show_right_detail = true;
    },
    to_show_match_edit(item) {
      console.log(item);
      this.$router.push({
        name: "match_manage_edit",
        query: {
          editing_obj_id: item.id,
          which_button: 2
        }
      });
    },

    to_show_open_edit(item) {
      console.log(item);

      this.table_item_click(item);
      this.$router.push({
        name: "match_manage_edit",
        query: {
          editing_obj_id: item.id,
          which_button: 1
        }
      });
    },

    compute_scrollarea_style() {
      this.$nextTick(() => {
        let hq = height(
          document.getElementById("match-manage-toggle-query-area")
        );
        // 获取筛选数据(select)的高度
        let select;
        if (this.$refs.select) {
          select = height(this.$refs.select);
        }
        select = select || 0;
        let hs = this.window_size_info.height - 36 - 30 - hq - 44;
        this.scroll_area_height = hs - 60 - select;
      });
    },
    compute_right_component_style() {
      let wh = this.window_size_info.height;
      let wc = wh - 36 - 30 - 30;
      let obj = {
        height: wc + "px",
        maxHeight: wc + "px"
      };
      this.right_component_style = obj;
      return obj;
    },
    handle_associate_or_merge_match_pre_confirm() {
      // 操作前确认 前置处理
      /**
       * 已经开赛的  不能 进行关联 和 合并操作
       */
      let cando = true;
      // let tsnow = new Date().getTime() - 8 * 60 * 60 * 1000;
      // for (let x = 0; x < this.selected_item_pool.length; x++) {
      //   if (this.selected_item_pool[x].beginTime <= tsnow) {
      //     let message = `当前选择条目中存在已开赛数据!`;
      //     this.show_alert_dialog(message);
      //     cando = false;
      //     break;
      //   }
      // }
      // return cando;
      return true;
    },
    handle_associate_match() {
      if (
        this.selected_item_standard_arr.length +
          this.selected_item_unstandard_arr.length ==
        1
      ) {
        // 单条 数据 提升标准
        this.handle_associate_match_onOk();
      } else {
        /**
         *  多条数据 开盘 存在以下情况
         * 关联赛事—常规关联                     handle_associate_match_case1
         * 关联赛事—未开盘时关联已关联数据         handle_associate_match_case1
         * 关联赛事—未开盘数据关联已开盘数据       handle_associate_match_case1
         * 关联赛事—已开盘数据关联已开盘数据       handle_associate_match_case2
         * 关联赛事—与联赛库关联不一致                后台处理
         *
         *  */
        this.handle_associate_match_case1();
      }
    },
    handle_associate_match_case1() {
      let message = "";
      message = alert_component.Association_carry_on("赛事");
      this.begin_script_dialog_process(
        message,
        this.handle_associate_match_onOk
      );
    },

    handle_associate_match_case2() {},
    handle_associate_match_onOk() {
      // 必须 有两条数据 商
      // 单条  BC 可以直接 通过生成联赛ID 直接 两次调用 生成 标准联赛 并生成联赛ID
      let params = {
        sourceId: [],
        standardId: ""
      };
      if (this.selected_item_standard_arr[0]) {
        params.standardId = this.selected_item_standard_arr[0]["id"];
      }
      this.selected_item_unstandard_arr.map(x => {
        params.sourceId.push(x.id);
      });
      api_match
        .post_matchManager_associate(params)
        .then(res => {
          let code = this.$lodash.get(res, "data.code");
          if (code == 200) {
            let data = this.$lodash.get(res, "data.data.records")[0];
            this.handle_dialog_onOk_callback_success(
              alert_component.success,
              () => {
                console.log(data);
                this.selected_item_pool_rebase();
                let arr = this.rebuild_tabledata_to_needed([data]);
                data = arr[0];
                data.is_selected = true;
                this.selected_table_items_change(data);

                this.show_associate_success = true;
                this.init_tabledata_force();
              }
            );
          } else {
            this.handle_dialog_onOk_callback_error(alert_component.failure);
            this.alert_message(res);
          }
        });
    },
    handle_merge_match() {
      //  多条标准赛事
      if (
        this.selected_item_standard_arr.length +
          this.selected_item_unstandard_arr.length ==
        1
      ) {
        // 单条 数据 提升标准
        this.handle_associate_match_onOk();
      } else {
        /**
         *
         * 合并赛事—未开盘数据合并已开盘数据       handle_merge_match_case1
         * 合并赛事—已开盘数据合并已开盘数据       handle_merge_match_case2
         *
         *  */
        // 判断是否都开盘分流operateMatchStatus 1 是开盘状态
        let flag = true;
        this.selected_item_standard_arr.forEach(x => {
          flag = x.operateMatchStatus === 1;
        });
        this.selected_item_unstandard_arr.forEach(x => {
          flag = x.operateMatchStatus === 1;
        });
        if (flag) {
          this.handle_merge_match_case2();
        } else {
          this.handle_merge_match_case1();
        }
      }
    },
    handle_merge_match_case1() {
      let message = alert_component.Association_carry_on("赛事");
      this.begin_script_dialog_process(message, this.handle_merge_match_onOk);
    },
    handle_merge_match_case2() {
      let message = alert_component.merge_carry_on;
      this.begin_script_dialog_process(message);
    },
    handle_merge_match_onOk() {
      let params = {
        standardMatchInfoIds: []
      };
      this.selected_item_standard_arr.map(x => {
        params.standardMatchInfoIds.push(x.id);
      });
      api_match
        .post_matchManager_merge(params)
        .then(res => {
          let code = this.$lodash.get(res, "data.code");
          if (code == 200) {
            let data = this.$lodash.get(res, "data.data.records")[0];
            console.log(data);
            this.handle_dialog_onOk_callback_success(
              alert_component.merge_success,
              () => {
                console.log(data);
                this.selected_item_pool_rebase();
                let arr = this.rebuild_tabledata_to_needed([data]);
                data = arr[0];
                data.is_selected = true;
                this.selected_table_items_change(data);
                this.show_associate_success = true;

                this.init_tabledata_force();
              }
            );
          } else {
            this.handle_dialog_onOk_callback_error(
              alert_component.merge_failure
            );
            this.alert_message(res);
          }
        });
    }
  },
  // 缓存路由回来执行
  activated() {
    this.init_tabledata_force();
  }
};
</script>
